package com.lisa.auto.scheduled;

import com.alibaba.fastjson.JSONArray;
import com.lisa.auto.entity.C3ReportCarFault;
import com.lisa.auto.entity.C3ReportCarInfo;
import com.lisa.auto.service.C3ReportCarFaultService;
import com.lisa.auto.service.C3ReportCarInfoService;
import com.lisa.redis.JedisClusterUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: huangzhigang
 * @date: 2020-04-23 10:18
 **/
@Component
public class CarCondRecHandle {

    public static final String KEY_ = "AUTO_";
    public static final String KEY_1 = "AUTO_1_";

    private static final Logger LOGGER = LoggerFactory.getLogger(CarCondRecHandle.class);

    private boolean isRunning = false;

    @Autowired
    private C3ReportCarInfoService c3ReportCarInfoService;
    @Autowired
    private C3ReportCarFaultService c3ReportCarFaultService;

    @Scheduled(cron = "0 0/1 * * * ? ")
    public void handle() {
        if (isRunning) {
            return;
        }
        try {
            isRunning = true;
            Map<String, String> fKeys = JedisClusterUtil.hGetAll(KEY_);

            Iterator<Map.Entry<String, String>> iterator = fKeys.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, String> entry = iterator.next();
                String fKey = entry.getKey();
                String data = JedisClusterUtil.hGet(KEY_, fKey);
                LOGGER.debug("redis data : {} ", data);
                if (StringUtils.isBlank(data)){
                    return;
                }
                List<C3ReportCarInfo> carInfos = JSONArray.parseArray(data, C3ReportCarInfo.class);
                List<C3ReportCarFault> faults = JSONArray.parseArray(data, C3ReportCarFault.class);
                if (!CollectionUtils.isEmpty(carInfos)) {
                    c3ReportCarInfoService.reportCarHandle(carInfos);
                }
                if (!CollectionUtils.isEmpty(faults)) {
                    c3ReportCarFaultService.reportCarFault(faults);
                }
                JedisClusterUtil.hDel(KEY_, fKey);
            }
        } catch (Exception e) {
            LOGGER.info(e.getMessage(), e);
        } finally {
            isRunning = false;
        }
    }
}
